1   /*
2    * Copyright (C) 2011 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.cache;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.Beta;
22  import com.google.common.annotations.GwtCompatible;
23  import com.google.common.annotations.GwtIncompatible;
24  import com.google.common.base.Function;
25  import com.google.common.base.Supplier;
26  import com.google.common.util.concurrent.Futures;
27  import com.google.common.util.concurrent.ListenableFuture;
28  import com.google.common.util.concurrent.ListenableFutureTask;
29  
30  import java.io.Serializable;
31  import java.util.Map;
32  import java.util.concurrent.Callable;
33  import java.util.concurrent.Executor;
34  
35  /**
36   * Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache}.
37   *
38   * <p>Most implementations will only need to implement {@link #load}. Other methods may be
39   * overridden as desired.
40   *
41   * <p>Usage example: <pre>   {@code
42   *
43   *   CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() {
44   *     public Graph load(Key key) throws AnyException {
45   *       return createExpensiveGraph(key);
46   *     }
47   *   };
48   *   LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader);}</pre>
49   *
50   * @author Charles Fry
51   * @since 10.0
52   */
53  @GwtCompatible(emulated = true)
54  public abstract class CacheLoader<K, V> {
55    /**
56     * Constructor for use by subclasses.
57     */
58    protected CacheLoader() {}
59  
60    /**
61     * Computes or retrieves the value corresponding to {@code key}.
62     *
63     * @param key the non-null key whose value should be loaded
64     * @return the value associated with {@code key}; <b>must not be null</b>
65     * @throws Exception if unable to load the result
66     * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
67     *     treated like any other {@code Exception} in all respects except that, when it is caught,
68     *     the thread's interrupt status is set
69     */
70    public abstract V load(K key) throws Exception;
71  
72    /**
73     * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This
74     * method is called when an existing cache entry is refreshed by
75     * {@link CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
76     *
77     * <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be
78     * overridden with an asynchronous implementation when using
79     * {@link CacheBuilder#refreshAfterWrite}.
80     *
81     * <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
82     *
83     * @param key the non-null key whose value should be loaded
84     * @param oldValue the non-null old value corresponding to {@code key}
85     * @return the future new value associated with {@code key};
86     *     <b>must not be null, must not return null</b>
87     * @throws Exception if unable to reload the result
88     * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
89     *     treated like any other {@code Exception} in all respects except that, when it is caught,
90     *     the thread's interrupt status is set
91     * @since 11.0
92     */
93    @GwtIncompatible("Futures")
94    public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
95      checkNotNull(key);
96      checkNotNull(oldValue);
97      return Futures.immediateFuture(load(key));
98    }
99  
100   /**
101    * Computes or retrieves the values corresponding to {@code keys}. This method is called by
102    * {@link LoadingCache#getAll}.
103    *
104    * <p>If the returned map doesn't contain all requested {@code keys} then the entries it does
105    * contain will be cached, but {@code getAll} will throw an exception. If the returned map
106    * contains extra keys not present in {@code keys} then all returned entries will be cached,
107    * but only the entries for {@code keys} will be returned from {@code getAll}.
108    *
109    * <p>This method should be overriden when bulk retrieval is significantly more efficient than
110    * many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls
111    * to {@link LoadingCache#get} if this method is not overriden.
112    *
113    * @param keys the unique, non-null keys whose values should be loaded
114    * @return a map from each key in {@code keys} to the value associated with that key;
115    *     <b>may not contain null values</b>
116    * @throws Exception if unable to load the result
117    * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
118    *     treated like any other {@code Exception} in all respects except that, when it is caught,
119    *     the thread's interrupt status is set
120    * @since 11.0
121    */
122   public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
123     // This will be caught by getAll(), causing it to fall back to multiple calls to
124     // LoadingCache.get
125     throw new UnsupportedLoadingOperationException();
126   }
127 
128   /**
129    * Returns a cache loader based on an <i>existing</i> function instance. Note that there's no need
130    * to create a <i>new</i> function just to pass it in here; just subclass {@code CacheLoader} and
131    * implement {@link #load load} instead.
132    *
133    * @param function the function to be used for loading values; must never return {@code null}
134    * @return a cache loader that loads values by passing each key to {@code function}
135    */
136   @Beta
137   public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
138     return new FunctionToCacheLoader<K, V>(function);
139   }
140 
141   private static final class FunctionToCacheLoader<K, V>
142       extends CacheLoader<K, V> implements Serializable {
143     private final Function<K, V> computingFunction;
144 
145     public FunctionToCacheLoader(Function<K, V> computingFunction) {
146       this.computingFunction = checkNotNull(computingFunction);
147     }
148 
149     @Override
150     public V load(K key) {
151       return computingFunction.apply(checkNotNull(key));
152     }
153 
154     private static final long serialVersionUID = 0;
155   }
156 
157   /**
158    * Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need
159    * to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
160    * implement {@link #load load} instead.
161    *
162    * @param supplier the supplier to be used for loading values; must never return {@code null}
163    * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
164    *     key
165    */
166   @Beta
167   public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
168     return new SupplierToCacheLoader<V>(supplier);
169   }
170 
171   /**
172    * Returns a {@code CacheLoader} which wraps {@code loader}, executing calls to
173    * {@link CacheLoader#reload} using {@code executor}.
174    *
175    * <p>This method is useful only when {@code loader.reload} has a synchronous implementation,
176    * such as {@linkplain #reload the default implementation}.
177    *
178    * @since 17.0
179    */
180   @Beta
181   @GwtIncompatible("Executor + Futures")
182   public static <K, V> CacheLoader<K, V> asyncReloading(final CacheLoader<K, V> loader,
183       final Executor executor) {
184     checkNotNull(loader);
185     checkNotNull(executor);
186     return new CacheLoader<K, V>() {
187       @Override
188       public V load(K key) throws Exception {
189         return loader.load(key);
190       }
191 
192       @Override
193       public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
194         ListenableFutureTask<V> task = ListenableFutureTask.create(new Callable<V>() {
195           @Override
196           public V call() throws Exception {
197             return loader.reload(key, oldValue).get();
198           }
199         });
200         executor.execute(task);
201         return task;
202       }
203 
204       @Override
205       public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
206         return loader.loadAll(keys);
207       }
208     };
209   }
210 
211   private static final class SupplierToCacheLoader<V>
212       extends CacheLoader<Object, V> implements Serializable {
213     private final Supplier<V> computingSupplier;
214 
215     public SupplierToCacheLoader(Supplier<V> computingSupplier) {
216       this.computingSupplier = checkNotNull(computingSupplier);
217     }
218 
219     @Override
220     public V load(Object key) {
221       checkNotNull(key);
222       return computingSupplier.get();
223     }
224 
225     private static final long serialVersionUID = 0;
226   }
227 
228   static final class UnsupportedLoadingOperationException extends UnsupportedOperationException {}
229 
230   /**
231    * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
232    *
233    * @since 11.0
234    */
235   public static final class InvalidCacheLoadException extends RuntimeException {
236     public InvalidCacheLoadException(String message) {
237       super(message);
238     }
239   }
240 }